<!-- @format -->

<!-- 
    author: ptt,
    desc:   轮播图组件,运动到最后一张时重新组装数据
    time:   2023/11/17
 -->

<template>
    <div class="view-box">
        <div v-show="isShow" class="scroll-box">
            <img
                v-for="(item, idx) in state.list"
                :key="idx"
                :src="item.IMG"
                alt=""
            />
        </div>
        <!-- 无数据占位符 -->
        <NoData :data="state.list">
            <img src="@/assets/images/noImg.png" />
        </NoData>
    </div>
</template>

<script setup>
import {
    onMounted,
    reactive,
    ref,
    toRefs,
    watch,
    computed,
    nextTick
} from 'vue';
const props = defineProps({
    data: {
        type: Array,
        default: () => {
            return [{ IMG: '' }];
        }
    },
    // 运动间隔
    intervalTime: {
        type: Number,
        // required: true
        default: 1000
    },
    height: {
        type: Number,
        required: true
    }
});
const state = reactive({ list: [], isShow: true, timer: null });
const { list, isShow } = toRefs(state);
let i = 0; //计步器
let scrollPx = ref('0px');
let transitionStyle = 'all 0.8s';

watch(
    () => props.data,
    val => {
        const len = val.length;
        //拷贝一份数据
        state.list = val;
        state.timer = setInterval(() => {
            i++;
            transitionStyle = 'all 0.8s';
            // 滚动到拷贝数据的最后一张图片时
            if (i == len) {
                i = 0;
                const newArr = state.list.splice(0, len - 1);
                state.list.push(...newArr);
                transitionStyle = 'none 0.8s';
                console.log('newArr', newArr);
                // clearInterval(state.timer);
                // state.isShow = false;
                // scrollPx.value = `0px`;

                // setTimeout(() => {
                //     state.isShow = true;
                // }, 10);
            }
            // 向上滚动
            scrollPx.value = `-${i * props.height}px`;
        }, props.intervalTime);
    }
);
</script>

<style lang="scss" scoped>
.view-box {
    width: 100%;
    height: v-bind("props.height+'px'");
    overflow: hidden;
    border: 1px solid #ccc;
    .scroll-box {
        transform: translateY(v-bind('scrollPx'));
        transition: v-bind(transitionStyle);
        img {
            width: 100%;
            height: v-bind("props.height+'px'");
            // 去掉img之间的间距
            vertical-align: top;
        }
    }
}
</style>
